﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using nwrole.toolbox.sync.contract;
using System.Data;
using System.Data.SqlClient;

namespace sync_web
{
    public class TestService : ITestService
    {
        #region lockRegion

        public class LockClass {

            public Object locker = new Object();

            int lockCounter = 0;
            int instanceCounter = 0;

            public LockClass() {
                instanceCounter++;
                if (instanceCounter != 1)
                {
                    throw new Exception("LockClass error");
                }
            }

            public void Lock()
            {
                lockCounter++;
                if (lockCounter != 1)
                {
                    throw new Exception("Lock error");
                }
            }

            public void Unlock()
            {
                lockCounter--;
                if (lockCounter != 0)
                {
                    throw new Exception("Unlock error");
                }
            }
        }

        static readonly LockClass LockObject = new LockClass();

        #endregion    

        public void ProcessMessage(SyncMessageEnvelope message)
        {
            // RunCommand(commandName, message.MessageData, false, true);
            //int startTheFun = 1;

            lock (LockObject.locker)
            {
                try
                {
                    LockObject.Lock();

                    string commandName1 = string.Format("[LoadMessage]", message.MessageType);
                    long msgId = RunCommand2(commandName1, message.MessageType, message.ClientCode, message.MsgCorr);

                    string commandName2 = string.Format("[Load_{0}]", message.MessageType);
                    DataTable dataTable = message.AsDataTable();
                    RunCommand(commandName2, dataTable, msgId, null, null);

                }
                catch (Exception e)
                {
                    // PluginLogger.LogException(KällTyp.Plugin, "BackOfficeServiceHostSyncPlugin", e, 0);
                    // SimplePlugin.EventLogger_LogException("BackOfficeInbox", e);

                    System.Console.WriteLine(e.ToString());
                    throw;
                }
                finally {
                    LockObject.Unlock();
                }
            }
            System.Console.WriteLine("done:" + DateTime.Now.ToString());

        }

        #region util



        private int nullCheckInt(int? l)
        {
            if (l.HasValue)
            {
                return l.Value;
            }
            return 0;
        }

        private bool nullCheckBool(bool? l)
        {
            if (l.HasValue)
            {
                return l.Value;
            }
            return false;
        }

        private double nullCheckDouble(double? l)
        {
            if (l.HasValue)
            {
                return l.Value;
            }
            return 0;
        }

        private long nullCheckLong(long? l)
        {
            if (l.HasValue)
            {
                return l.Value;
            }
            return -999;
        }

        private string nullCheckString2(string l, int maxLength)
        {
            if (l == null)
            {
                return "";
            }
            if (l.Length > maxLength)
            {
                return "length error";
            }
            return l;
        }

        private DateTime nullCheckDate(DateTime? d)
        {
            if (d.HasValue)
            {
                return d.Value;
            }
            return new DateTime(1899, 1, 1);
        }

        protected void RunCommand(String sql, DataTable dataTable)
        {
            RunCommand(sql, dataTable, null, null, null);
        }

        protected void RunCommand(String sql, DataTable dataTable, long? msgId, bool? first, bool? last)
        {
            using (SqlConnection connection = new SqlConnection(ConnectionUtil.GetConnectionString()))
            {
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    command.CommandType = System.Data.CommandType.StoredProcedure;

                    if (msgId.HasValue)
                    {
                        SqlParameter msgIdParam = new SqlParameter();
                        msgIdParam.ParameterName = "@msgId";
                        msgIdParam.SqlDbType = System.Data.SqlDbType.BigInt;
                        msgIdParam.Value = msgId.Value;
                        command.Parameters.Add(msgIdParam);
                    }

                    if (first.HasValue)
                    {
                        SqlParameter firstParam = new SqlParameter();
                        firstParam.ParameterName = "@firstMessage";
                        firstParam.SqlDbType = System.Data.SqlDbType.Bit;
                        firstParam.Value = first.Value;
                        command.Parameters.Add(firstParam);
                    }

                    if (last.HasValue)
                    {
                        SqlParameter lastParam = new SqlParameter();
                        lastParam.ParameterName = "@lastMessage";
                        lastParam.SqlDbType = System.Data.SqlDbType.Bit;
                        lastParam.Value = last.Value;
                        command.Parameters.Add(lastParam);
                    }

                    if (dataTable != null)
                    {
                        SqlParameter parameter = new SqlParameter();
                        parameter.ParameterName = "@myData";
                        parameter.SqlDbType = System.Data.SqlDbType.Structured;
                        parameter.Value = dataTable;
                        command.Parameters.Add(parameter);
                    }

                    connection.Open();
                    command.ExecuteNonQuery();
                }
            }
        }

        protected long RunCommand2(String sql, string messageType, string clientCode, Guid guid)
        {
            using (SqlConnection connection = new SqlConnection(ConnectionUtil.GetConnectionString()))
            {
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    command.CommandType = System.Data.CommandType.StoredProcedure;

                    if (messageType != null)
                    {
                        SqlParameter msgIdParam = new SqlParameter();
                        msgIdParam.ParameterName = "@messageType";
                        msgIdParam.SqlDbType = System.Data.SqlDbType.NVarChar;
                        msgIdParam.Size = 40;
                        msgIdParam.Value = messageType;
                        command.Parameters.Add(msgIdParam);
                    }

                    if (clientCode != null)
                    {
                        SqlParameter clientCodeParam = new SqlParameter();
                        clientCodeParam.ParameterName = "@clientCode";
                        clientCodeParam.SqlDbType = System.Data.SqlDbType.NVarChar;
                        clientCodeParam.Size = 20;
                        clientCodeParam.Value = messageType;
                        command.Parameters.Add(clientCodeParam);
                    }

                    if (guid != null)
                    {
                        SqlParameter guidParam = new SqlParameter();
                        guidParam.ParameterName = "@messageGuid";
                        guidParam.SqlDbType = System.Data.SqlDbType.UniqueIdentifier;
                        guidParam.Value = guid;
                        command.Parameters.Add(guidParam);
                    }

/*                    if (first.HasValue)
                    {
                        SqlParameter firstParam = new SqlParameter();
                        firstParam.ParameterName = "@firstMessage";
                        firstParam.SqlDbType = System.Data.SqlDbType.Bit;
                        firstParam.Value = first.Value;
                        command.Parameters.Add(firstParam);
                    }

                    if (last.HasValue)
                    {
                        SqlParameter lastParam = new SqlParameter();
                        lastParam.ParameterName = "@lastMessage";
                        lastParam.SqlDbType = System.Data.SqlDbType.Bit;
                        lastParam.Value = last.Value;
                        command.Parameters.Add(lastParam);
                    }
*/
                    connection.Open();
                    // object o = command.ExecuteScalar();
                    decimal? result = command.ExecuteScalar() as decimal?;
                    if (result.HasValue) return Convert.ToInt64(result.Value);
                    return 0;
                }
            }
        }

        #endregion
    }
}
